/*UDP双向循环——客户端*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

void* recvfromser(void *arg)
{
	char buf[50];
	int fd = *(int*)arg;

	pthread_detach(pthread_self());
	while(1)
	{
		bzero(buf,50);
		recvfrom(fd,buf,50,0,NULL,NULL);
		printf("server>>>%s",buf);
	}

	return NULL;
}

int main(void)
{
	int fd;
	int ret;
	
	//创建socket
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd == -1) 
	{
		perror("socket");
		exit(1);
	}

	//初始化客户端socket地址
	struct sockaddr_in client;
	client.sin_family = AF_INET;
	client.sin_addr.s_addr = inet_addr("192.168.104.89");
	client.sin_port = htons(10000);
	ret = bind(fd, (struct sockaddr *)&client, sizeof(client));
	if (ret == -1) 
	{
		perror("bind");
		exit(1);
	}

	/*创建接收线程*/
	pthread_t tid;
	pthread_create(&tid,NULL,recvfromser,&fd);

	//发送
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("192.168.104.89");
	server.sin_port = htons(10001);
	char buf[50];
	
	while (1) 
	{
		bzero(buf, 50);
		fgets(buf, 50, stdin);
		sendto(fd, buf, strlen(buf), 0, (struct sockaddr*)&server, sizeof(server));
	}
	
	//关闭socket
	close(fd);
	
	return 0;
}

